









# import requests




# def wechat_pay():
#     goods_price = request.args.get("price")
#     openid = g.current_user.get("openId")
#     appid = ""  #小程序appid,小程序-开发-开发设置里找
#     mch_id = "" #微信支付商户号，微信支付|商户平台-账户中心-商户信息里找
#     api_key = "" #API秘钥，微信支付|商户平台-账户中心-API安全里找
#     notify_url = "" #支付成功回调路径
#     orderid = datetime.datetime.now().strftime('%Y%m%d%H%M%S')  #已时间为订单号
#     info = WX_PayToolUtil(appid, mch_id, api_key, notify_url)
#     data = info.getPayUrl(orderid, openid, goods_price)
#     return json_response(0, data=data)




# coding=utf-8
import requests
import hashlib
import xmltodict
import time
import json
import random
import string
from random import Random

APP_ID = "wx01e315a1f1f0d156"
MCH_ID = "1649420995"
API_KEY="f3e000bbfeb4c5e7e7dbecb2717eb471"
NOTIFY_URL="https://wnh.e-nex.cn"
# openid= ""

class WX_PayToolUtil():
    """ 微信支付工具 """
    def __init__(self, APP_ID, MCH_ID, API_KEY, NOTIFY_URL):
        self._APP_ID = "wx01e315a1f1f0d156" # 小程序ID
        self._MCH_ID = "1649420995" # # 商户号
        self._API_KEY = API_KEY # 商户秘钥
        self._UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder" # 接口链接
        self._NOTIFY_URL = "https://wnh.e-nex.cn" # 异步通知


    def generate_sign(self, param):
        '''生成签名'''
        stringA = ''
        ks = sorted(param.keys())# 参数按键值排序
        for k in ks:
            stringA += (k + '=' + param[k] + '&')
        # 拼接商户KEY
        stringSignTemp = stringA + "key=" + self._API_KEY
        # md5加密,也可以用其他方式
        hash_md5 = hashlib.md5(stringSignTemp.encode('utf8'))
        sign = hash_md5.hexdigest().upper()
        return sign


    def random_str(self):
        """
        生成随机字符串
        :param randomlength: 字符串长度
        :return:
        """
        strs = ''
        chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
        length = len(chars) - 1
        random = Random()
        for i in range(0, 30):
            strs += chars[random.randint(0, length)]
        return strs


    def getPayUrl(self, orderid, openid, goodsPrice, **kwargs):
        """向微信支付端发出请求，获取url"""
        key = self._API_KEY
        nonce_str = self.random_str()# 生成随机字符串，小于32位
        params = {
            'appid': self._APP_ID, # 小程序ID
            'mch_id': self._MCH_ID, # 商户号
            'nonce_str': nonce_str, # 随机字符串
            "body": 'learning card', # 支付说明
            'out_trade_no': orderid, # 生成的订单号
            'total_fee': str(goodsPrice), # 标价金额
            'spbill_create_ip': "", # 终端IP,你服务器IP
            'notify_url': self._NOTIFY_URL,
            'trade_type': "JSAPI", # 支付类型
            "openid": openid, # 用户id
        }
        # 生成签名
        params['sign'] = self.generate_sign(params)
        param = {'root': params}
        xml = xmltodict.unparse(param)
        response = requests.post(self._UFDODER_URL, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'})
        # xml 2 dict
        msg = response.text
        xmlmsg = xmltodict.parse(msg)
        # 4. 获取prepay_id

        if xmlmsg['xml']['return_code'] == 'SUCCESS':
            prepay_id = xmlmsg['xml']['prepay_id']
            # 时间戳
            timeStamp = str(int(time.time()))
            # 5. 五个参数
            data = {
            "appId": self._APP_ID,
            "nonceStr": nonce_str,
            "package": "prepay_id=" + prepay_id,
            "signType": 'MD5',
            "timeStamp": timeStamp,
            }
            # 6. paySign签名
            paySign = self.generate_sign(data)
            data["paySign"] = paySign # 加入签名
            # 7. 传给前端的签名后的参数
            return data



def get_open_id(appid,code,secret):
    url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code".format(appid=appid,secret=secret,code=code)
    # 发送网络请求，获取用户的openid
    response = requests.get(url)
    data = json.loads(response.text)
    openid = data.get('openid')
    return openid


orderid ="202307311413fijsgjowjf"
goodsPrice = 3000
code = ""
appid = "wx01e315a1f1f0d156"
secret = "599210b768dd0bcf7ef8c63701003da4"
openid = get_open_id(appid,code,secret)
WX_PayToolUtil(APP_ID, MCH_ID, API_KEY, NOTIFY_URL).getPayUrl( orderid, openid, goodsPrice)


















